#include "debug-helper.h"
#include "double-spin-box-delegate.h"
#include "line-edit-delegate.h"
#include "product-section-model.h"
#include "product-section-queries.h"
#include "spin-box-delegate.h"
#include "value-result.h"

ProductSectionModel::ProductSectionModel(QObject *parent) :
    StandardDatabaseModel(parent)
{
}

void ProductSectionModel::initialize()
{
    setupQueries();
    LineEditDelegate* nameDelegate = new LineEditDelegate(this);
    DoubleSpinBoxDelegate* priceDelegate = new DoubleSpinBoxDelegate(this);
    SpinBoxDelegate* vatDelegate = new SpinBoxDelegate(this);
    SpinBoxDelegate* quantityDelegate = new SpinBoxDelegate(this);
    m_delegates.insert(NameColumn, nameDelegate);
    m_delegates.insert(PriceColumn, priceDelegate);
    m_delegates.insert(VatColumn, vatDelegate);
    m_delegates.insert(QuantityColumn, quantityDelegate);
    m_headerSections << "Nazwa" << "Cena" << "VAT" << "Ilość";
    m_dataAlreadyExistText = "Produkt o takich danych już istnieje.";
    StandardDatabaseModel::initialize();
}

void ProductSectionModel::setupQueries()
{
    m_queries = new ProductSectionQueries(this);
}

void ProductSectionModel::setupInternalModel()
{
    StandardDatabaseModel::setupInternalModel();

    for (int i = 0; i < rowCount(); i++)
    {
        // sum column
        QString price = QLocale().toString(m_internalModel->index(i, PriceColumn+m_idColumnCount).data().toDouble(), 'f', 2);
        m_internalModel->setData(m_internalModel->index(i, PriceColumn+m_idColumnCount), price, Qt::DisplayRole);
    }
}

ValueResult* ProductSectionModel::canSetField (QVariant value, int column, int row)
{
    Q_UNUSED(row);
    ValueResult* result = new ValueResult(this);
    if (column == NameColumn)
    {
        QString name(value.toString());
        if (name.isEmpty())
            result->setError("Nazwa kontrahenta jest pusta.", SmGlobal::DataInvalidError);
        else
            result->setValue(true);
    }
    else if (column == PriceColumn)
    {
        bool ok = false;
        correctedValue(value, column).toDouble(&ok);
        if (!ok)
            result->setError("Cena jest nieprawidłowa.", SmGlobal::DataInvalidError);
        else
            result->setValue(true);
    }
    else if (column == VatColumn)
    {
        bool ok = false;
        value.toInt(&ok);
        if (!ok)
            result->setError("VAT jest nieprawidłowy.", SmGlobal::DataInvalidError);
        else
            result->setValue(true);
    }
    else if (column == QuantityColumn)
    {
        bool ok = false;
        value.toInt(&ok);
        if (!ok)
            result->setError("Ilość jest nieprawidłowa.", SmGlobal::DataInvalidError);
        else
            result->setValue(true);
    }
    else
    {
        fatalError(column);
        return 0;
    }
    return result;
}
